package com.bootdo.order.service.impl;

import static com.bootdo.common.utils.ShiroUtils.getUser;
import static com.bootdo.common.utils.ShiroUtils.getUserId;

import java.text.NumberFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.merchant.dao.MerchantDao;
import com.bootdo.merchant.domain.MerchantDO;
import com.bootdo.order.dao.OrderPayDao;
import com.bootdo.order.dao.RechargeDao;
import com.bootdo.order.domain.OrderPayDO;
import com.bootdo.order.domain.RechargeDO;
import com.bootdo.order.service.ProfitService;
import com.bootdo.quota.dao.QuotaDao;
import com.bootdo.quota.domain.QuotaDO;

/**
 * @Desc 收入统计
 * @date 2019/12/25
 *
 */
@Service
public class ProfitServiceImpl implements ProfitService {

    @Autowired
    private OrderPayDao orderPayMapper;
    @Autowired
    private QuotaDao quotaMapper;
    @Autowired
    private RechargeDao rechargeMapper;
    @Autowired
    private MerchantDao merchantMapper;

    @Override
    public Map<String, Object> list(Map<String, Object> map){
        //格式话日期
        String startDate = (String) map.get("startTime");
        String endDate = (String) map.get("endTime");
        if (StringUtils.isNotBlank(startDate)){
            startDate = DateUtils.getDateOfFormat(startDate, DateUtils.DATE_TIME_PATTERN);
            endDate = DateUtils.getDateOfFormat(endDate, DateUtils.DATE_TIME_PATTERN);
            map.put("startTime", startDate);
            map.put("endTime", endDate);
        }

        Map<String, Object> uMap = new HashMap<>();
        List<Long> role = getUser().getRoleIds();
        for (Long roleId : role){
            if (roleId != 1L && roleId != 64L){
                map.put("userId", getUserId());
                uMap.put("roleId", roleId);
                break;
            }
        }
        List<OrderPayDO> orders = orderPayMapper.list(map);
        //总订单数
        int count = orders.size();
        //总成功数
        int countOk = 0;
        //支付宝总订单数
        int aliCode = 0;
        //微信总订单数
        int weixinCode = 0;
        //支付宝转账总订单数
        int alipay = 0;
        //支付宝账号转账总订单数
        int alipayAccount = 0;
        //总订单金额
        double countMoney = 0.0;
        //总手续费
        double countCharge = 0.0;
        //平台总利润
        double platMoney = 0.0;
        //商代总佣金
        double merAgentMoney = 0.0;
        //商户总金额
        double merMoney = 0.0;
        //收款户代理总佣金
        double payeeAgentMoney = 0.0;
        //收款户代理纯利润
        double payeeAgentMoneys = 0.0;
        //收款户代理余额
        double payeeAgentBalance = 0.0;
        //收款户代理充值总额
        double payeeAgentRecharge = 0.0;

        //商户可提现金额
        double merRecordMoney = 0.0;
        //商户代理可提现金额
        double merAgentRecordMoney = 0.0;

        //今日订单量
        int todayCount = 0;
        //今日成功量
        int todayCountOk = 0;
        //今日支付宝订单数
        int todayAliCode = 0;
        //今日微信订单数
        int todayWeixinCode = 0;
        //今日支付宝转账订单数
        int todayAlipay = 0;
        //今日支付宝账号转账订单数
        int todayAlipayAccount = 0;
        //今日总订单金额
        double todayCountMoney = 0.0;
        //今日总手续费
        double todayCountCharge = 0.0;
        //今日平台总利润
        double todayPlatMoney = 0.0;
        //今日商代总佣金
        double todayMerAgentMoney = 0.0;
        //今日商户总金额
        double todayMerMoney = 0.0;
        //今日收款户代理总佣金
        double todayPayeeAgentMoney = 0.0;

        Set<Long> payeeAgents = new HashSet<>();
        Set<Long> merchants = new HashSet<>();
        for (OrderPayDO orderPay : orders){
            if (DateUtils.isToday(orderPay.getGmtCreate())){
                todayCount++;
            }
            if (1 != orderPay.getStatus() && 4 != orderPay.getStatus()) {
                platMoney += Math.round(orderPay.getPlatformMoney() * 100);
                merAgentMoney += (orderPay.getMerchantMoney() == null ? 0.00 : Math.round(orderPay.getMerchantMoney() * 100));
                merMoney += (Math.round(orderPay.getOrderMoney() * 100) - Math.round(orderPay.getCountMoney() * 100));
                payeeAgentMoney += Math.round(orderPay.getPayeeAgentMoney() * 100) + Math.round(orderPay.getPayeeMoney() * 100);
                payeeAgentMoneys += Math.round(orderPay.getPayeeAgentMoney() * 100);
                payeeAgents.add(orderPay.getPayeeAgentId());
                merchants.add(orderPay.getMerchantId());

                countMoney += Math.round(orderPay.getOrderMoney() * 100);
                countCharge += Math.round(orderPay.getCountMoney() * 100);
                countOk++;

                //当日数据
                if (DateUtils.isToday(orderPay.getGmtCreate())){
                    todayPlatMoney += Math.round(orderPay.getPlatformMoney() * 100);
                    todayMerAgentMoney += (orderPay.getMerchantMoney() == null ? 0.00 : Math.round(orderPay.getMerchantMoney() * 100));
                    todayMerMoney += (Math.round(orderPay.getOrderMoney() * 100) - Math.round(orderPay.getCountMoney() * 100));
                    todayPayeeAgentMoney += Math.round(orderPay.getPayeeAgentMoney() * 100) + Math.round(orderPay.getPayeeMoney() * 100);

                    todayCountMoney += Math.round(orderPay.getOrderMoney() * 100);
                    todayCountCharge += Math.round(orderPay.getCountMoney() * 100);
                    todayCountOk++;
                }

                if (1 == orderPay.getPayType().intValue()) {
                    //支付宝固码
                    aliCode++;
                    if (DateUtils.isToday(orderPay.getGmtCreate())){
                        todayAliCode++;
                    }
                } else if (2 == orderPay.getPayType()) {
                    //微信固码
                    weixinCode++;
                    if (DateUtils.isToday(orderPay.getGmtCreate())){
                        todayWeixinCode++;
                    }
                } else if (3 == orderPay.getPayType()){
                    alipay++;
                    if (DateUtils.isToday(orderPay.getGmtCreate())){
                        todayAlipay++;
                    }
                } else if (4 == orderPay.getPayType()){
                    alipayAccount++;
                    if (DateUtils.isToday(orderPay.getGmtCreate())){
                        todayAlipayAccount++;
                    }
                }
            }
        }
        //获取收款户代理余额
        for (Long userId : payeeAgents){
            QuotaDO quota = quotaMapper.get(userId);
            payeeAgentBalance += Math.round(quota.getActualQuota() * 100);

            List<RechargeDO> lists = rechargeMapper.queryRechargeOk(userId);
            for (RechargeDO recharge : lists){
                payeeAgentRecharge += Math.round(recharge.getMoney() * 100);
            }
        }

        //获取商户代理和商户可提现总额
        Set<Long> agentIds = new HashSet<>();
        for (Long userId : merchants) {
            MerchantDO merchant = merchantMapper.get(userId);
            QuotaDO quota = quotaMapper.get(userId);
            merRecordMoney += Math.round(quota.getActualQuota() * 100);

            if (1 != merchant.getUserIdCreate() && 2 != merchant.getUserIdCreate()){
               agentIds.add(merchant.getUserIdCreate());
            }

        }
        for (Long userId : agentIds) {
            QuotaDO quota = quotaMapper.get(userId);
            if (quota != null){
                merAgentRecordMoney += Math.round(quota.getActualQuota() * 100);
            }
        }

        uMap.put("count", count);
        uMap.put("countOk", countOk);
        uMap.put("aliCode", aliCode);
        uMap.put("weixinCode", weixinCode);
        uMap.put("alipay", alipay);
        uMap.put("alipayAccount", alipayAccount);
        uMap.put("countMoney", countMoney/100);
        uMap.put("countCharge", countCharge/100);
        uMap.put("platMoney", platMoney/100);
        uMap.put("merAgentMoney", merAgentMoney/100);
        uMap.put("merMoney", merMoney/100);
        uMap.put("payeeAgentMoney", payeeAgentMoney/100);
        uMap.put("payeeAgentBalance", payeeAgentBalance/100);
        uMap.put("payeeAgentRecharge", payeeAgentRecharge/100);
        uMap.put("merRecordMoney", merRecordMoney/100);
        uMap.put("merAgentRecordMoney", merAgentRecordMoney/100);
        uMap.put("payeeAgentMoneys", payeeAgentMoneys/100);
        //今日数据
        uMap.put("todayCount", todayCount);
        uMap.put("todayCountOk", todayCountOk);
        uMap.put("todayAliCode", todayAliCode);
        uMap.put("todayWeixinCode", todayWeixinCode);
        uMap.put("todayAlipay", todayAlipay);
        uMap.put("todayAlipayAccount", todayAlipayAccount);
        uMap.put("todayCountMoney", todayCountMoney/100);
        uMap.put("todayCountCharge", todayCountCharge/100);
        uMap.put("todayPlatMoney", todayPlatMoney/100);
        uMap.put("todayMerAgentMoney", todayMerAgentMoney/100);
        uMap.put("todayMerMoney", todayMerMoney/100);
        uMap.put("todayPayeeAgentMoney", todayPayeeAgentMoney/100);

        if (count > 0){
            NumberFormat format = NumberFormat.getPercentInstance();
            format.setMaximumFractionDigits(2);
            double accuracy = (double)countOk / (double)count;
            uMap.put("countOkCharge", format.format(accuracy));
        } else {
            uMap.put("countOkCharge", 0);
        }

        if (todayCount > 0){
            NumberFormat format = NumberFormat.getPercentInstance();
            format.setMaximumFractionDigits(2);
            double accuracy = (double)todayCountOk / (double)todayCount;
            uMap.put("todayOkCharge", format.format(accuracy));
        } else {
            uMap.put("todayOkCharge", 0);
        }
        return uMap;
    }

    @Override
    public Map<String, String> queryP(Map<String, Object> map){
        //格式话日期
        String startDate = (String) map.get("startTime");
        String endDate = (String) map.get("endTime");
        if (StringUtils.isNotBlank(startDate)){
            startDate = DateUtils.getDateOfFormat(startDate, DateUtils.DATE_TIME_PATTERN);
            endDate = DateUtils.getDateOfFormat(endDate, DateUtils.DATE_TIME_PATTERN);
            map.put("startTime", startDate);
            map.put("endTime", endDate);
        }
        List<Long> role = getUser().getRoleIds();
        for (Long roleId : role){
            if (roleId != 1L && roleId != 64L){
                map.put("userId", getUserId());
                break;
            }
        }
        List<OrderPayDO> orders = orderPayMapper.pList(map);
        double profits = 0.0;
        for (OrderPayDO orderPay : orders) {
            profits += Math.round(orderPay.getOrderMoney() * 100);
        }
        NumberFormat nf = NumberFormat.getInstance();
        Map<String, String> rMap = new HashMap<>();
        rMap.put("profit", String.valueOf(orders.size()));
        rMap.put("profits", nf.format(profits/100));
        return rMap;
    }

    @Override
    public Map<String, String> queryM(Map<String, Object> map){
        //格式话日期
        String startDate = (String) map.get("startTime");
        String endDate = (String) map.get("endTime");
        if (StringUtils.isNotBlank(startDate)){
            startDate = DateUtils.getDateOfFormat(startDate, DateUtils.DATE_TIME_PATTERN);
            endDate = DateUtils.getDateOfFormat(endDate, DateUtils.DATE_TIME_PATTERN);
            map.put("startTime", startDate);
            map.put("endTime", endDate);
        }
        List<Long> role = getUser().getRoleIds();
        for (Long roleId : role){
            if (roleId != 1L && roleId != 64L){
                map.put("userId", getUserId());
                break;
            }
        }
        List<OrderPayDO> orders = orderPayMapper.mList(map);
        double profits = 0.0;
        for (OrderPayDO orderPay : orders) {
            profits += Math.round(orderPay.getOrderMoney() * 100);
        }
        NumberFormat nf = NumberFormat.getInstance();
        Map<String, String> rMap = new HashMap<>();
        rMap.put("profit", String.valueOf(orders.size()));
        rMap.put("profits", nf.format(profits/100));
        return rMap;
    }

//    public Map<String, String> queryProfitByMerc(Map<String, Object> map){
//        //格式话日期
//        String startDate = (String) map.get("startTime");
//        String endDate = (String) map.get("endTime");
//        if (StringUtils.isNotBlank(startDate)){
//            startDate = DateUtils.getDateOfFormat(startDate, DateUtils.DATE_TIME_PATTERN);
//            endDate = DateUtils.getDateOfFormat(endDate, DateUtils.DATE_TIME_PATTERN);
//            map.put("startTime", startDate);
//            map.put("endTime", endDate);
//        }
//        List<Long> role = getUser().getRoleIds();
//        for (Long roleId : role){
//            if (roleId != 1L && roleId != 64L){
//                map.put("userId", getUserId());
//                break;
//            }
//        }
//        List<OrderPayDO> orders = orderPayMapper.mList(map);
//        double platMoney = 0.00;//平台总金额
//        double merMoney = 0.00;//商户余额
////        double merCash = 0.00;//商户已提现金额
//        double merAgentMoney = 0.00;//商户代理金额
////        double merAgentCash = 0.00;//商户代理已提现金额
//        List<Long> merchantIds = new ArrayList<>();
//        for (OrderPayDO orderPay : orders){
//            //订单金额
//            if (1 != orderPay.getStatus()) {
//                platMoney += orderPay.getPlatformMoney();
//                merAgentMoney += (orderPay.getMerchantMoney() == null ? 0.00 : orderPay.getMerchantMoney());
//                merMoney += (orderPay.getOrderMoney().doubleValue() - orderPay.getCountMoney().doubleValue());
//                //所有商户已提现金额
////                if (merchantId == null || orderPay.getMerchantId().longValue() != merchantId.longValue()){
////                    merchantId = orderPay.getMerchantId();
////                    List<CashDO> cashs = cashMapper.findMoneyCount(merchantId);
////                    for (CashDO cash : cashs){
////                        merCash += cash.getCashMoney();
////                    }
////                }
//                merchantIds.add(orderPay.getMerchantId());
//                //获取商户代理id
//            }
//        }
//
//        //所有商户已提现金额
//        List<CashDO> merCashs = cashMapper.findMoneyCountByIds(merchantIds);
//        double merCash = 0.00;
//        for (CashDO cash : merCashs){
//            merCash += cash.getCashMoney();
//        }
//
//        //已提现金额
//        List<CashDO> cashs = cashMapper.findMoneyCount(getUserId());
//        double cashMoney = 0.00;
//        for (CashDO cash : cashs){
//            cashMoney += cash.getCashMoney();
//        }
//        Map<String, String> rMap = new HashMap<>();
//        rMap.put("platMoney", String.valueOf(platMoney));
//        rMap.put("platCash", String.valueOf(platMoney - cashMoney));
//        rMap.put("merAgentMoney", String.valueOf(merAgentMoney));
//        rMap.put("merAgentCash", String.valueOf(merAgentMoney - cashMoney));
//        rMap.put("merMoney", String.valueOf(merMoney));
//        rMap.put("merCash", String.valueOf(merMoney - merCash));
//        rMap.put("cashMoney", String.valueOf(cashMoney));
//        rMap.put("count", String.valueOf(orders.size()));
//        rMap.put("role", String.valueOf(role.get(0)));
//
//        return rMap;
//    }
//
//    public Map<String, String> queryProfitByPayee(Map<String, Object> map){
//        //格式话日期
//        String startDate = (String) map.get("startTime");
//        String endDate = (String) map.get("endTime");
//        if (StringUtils.isNotBlank(startDate)){
//            startDate = DateUtils.getDateOfFormat(startDate, DateUtils.DATE_TIME_PATTERN);
//            endDate = DateUtils.getDateOfFormat(endDate, DateUtils.DATE_TIME_PATTERN);
//            map.put("startTime", startDate);
//            map.put("endTime", endDate);
//        }
//        List<Long> role = getUser().getRoleIds();
//        for (Long roleId : role){
//            if (roleId != 1L && roleId != 64L){
//                map.put("userId", getUserId());
//                break;
//            }
//        }
//        List<OrderPayDO> orders = orderPayMapper.pList(map);
//        double platMoney = 0.00;//平台总金额
//        double payeeMoney = 0.00;//收款户余额
//        double payeeAgentMoney = 0.00;//收款户代理金额
//        for (OrderPayDO orderPay : orders){
//            //订单金额
//            if (1 != orderPay.getStatus()) {
//                platMoney += orderPay.getPlatformMoney();
//                payeeAgentMoney += orderPay.getPayeeAgentMoney();
//                payeeMoney += orderPay.getPayeeMoney();
//            }
//        }
//
//        //已提现金额
//        List<CashDO> cashs = cashMapper.findMoneyCount(getUserId());
//        double cashMoney = 0.00;
//        for (CashDO cash : cashs){
//            cashMoney += cash.getCashMoney();
//        }
//        Map<String, String> rMap = new HashMap<>();
//        rMap.put("platMoney", String.valueOf(platMoney));
//        rMap.put("platCash", String.valueOf(platMoney - cashMoney));
//        rMap.put("payeeAgentMoney", String.valueOf(payeeAgentMoney));
//        rMap.put("payeeMoney", String.valueOf(payeeMoney));
//        rMap.put("cashMoney", String.valueOf(cashMoney));
//        rMap.put("count", String.valueOf(orders.size()));
//        rMap.put("role", String.valueOf(role.get(0)));
//
//        return rMap;
//    }
}
